package cfi;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.arnx.jsonic.JSON;
import cfi.jdo.CoffeeCustomer;
import cfi.jdo.PMF;
import cfi.jdo.Purchase;
import cfi.util.CfUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class CfiRegisServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String errorMessage = null;
		String joson = null;
		String idm = req.getParameter("idm");
		String uname = req.getParameter("unamd");
		if (idm == null || idm == "" || uname == null || uname == "") {
			errorMessage = "登録情報取得失敗。";
		} else {

			CoffeeCustomer c = new CoffeeCustomer(uname, CfUtil.getJPDate());
			Key key = KeyFactory.createKey(
					CoffeeCustomer.class.getSimpleName(), idm);
			c.setKey(key);
			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				pm.makePersistent(c);
				joson = JSON.encode(c);
			} catch (Exception e) {
				errorMessage = "登録に失敗。";
			} finally {
				pm.close();
			}
		}
		if (joson != null) {
			resp.setContentType("application/json; charset=UTF-8");
			resp.getWriter().println(joson);
		} else {
			resp.setContentType("text/plain");
			resp.setContentType("text/html;charset=UTF-8");
			resp.getWriter().println(errorMessage);
		}
	}
}
